import React from 'react';
import {FlatList, Image, StyleSheet, Text} from 'react-native';
import {TouchableOpacity, View, Button} from 'react-native-ui-lib';
import {commonStyles} from '../../configs/commonStyle';
import BasePage from '../BasePage';
import ListEmpty from '../common/ListEmpty';
import DateFilter from '../components/DateFilter';
import {inject, observer} from 'mobx-react';
import moment from 'moment';
import AbnormalDialog from './components/AbnormalDialog';
import {getTransferNoteList, removeOutbound} from '../../net/transfer';
import {IconImage} from '../../utils';
import ToastUtils from '../../utils/ToastUtils';
import {
  logger,
  setClipboardContent,
} from "../../utils/util";
const statusLabelMap = {
  1: '已出库',
  2: '中转中',
  3: '已完成',
};
const statusStyleMap = {
  1: commonStyles.text_gray_13,
  2: commonStyles.text_blue_13,
  3: commonStyles.text_green_13,
};

/**
 * 中转记录
 */
@inject('userStore', 'appStore')
@observer
export default class TransferList extends BasePage {
  constructor(props) {
    super(props);
    this.isLoading = false;
    this.state = {
      isRefreshing: false,
      showEmpty: false,
      dataList: [],
      timeStart: moment().format('YYYY-MM-DD'),
      timeEnd: moment().format('YYYY-MM-DD'),
    };
  }

  componentDidMount() {
    this.loadData(true);
  }

  loadData() {
    this.getTransferNoteList();
  }

  getTransferNoteList = () => {
    const {timeStart, timeEnd} = this.state;
    this.isLoading = true;
    getTransferNoteList({
      timeStart: `${timeStart} 00:00:00`,
      timeEnd: `${timeEnd} 23:59:59`,
      showLoading: true,
    })
      .then(res => {
        logger(res);
        if (!IsNullOrEmpty(res?.result)) {
          this.setState({
            dataList: res.result,
            isRefreshing: false,
            showEmpty: IsNullOrEmpty(res.result),
          });
        } else {
          this.setState({
            dataList: [],
            showEmpty: true,
          });
        }
      })
      .finally(() => {
        this.isLoading = false;
      });
  };

  // 移除蛋糕
  removeCake(cake) {
    const params = {
      orderDetailId: cake.orderDetailId
    }
    removeOutbound(params).then(res => {
      ToastUtils.showSuccessInfo('移除成功');
      this.loadData();
    }).catch(err => {
      ToastUtils.showFailInfo(err?.msg || '失败，请重试');
    });
  }

  // 下拉刷新
  _renderRefresh = () => {
    // 不处于 下拉刷新
    if (this.isLoading === false) {
      this.loadData();
    }
  };

  render_goods_item = (cake, item) => {
    return (
      <View style={{backgroundColor: '#EFEFEF'}} padding-10 marginB-10>
        <View row centerV>
          <Image
            source={
              cake?.status == 3 ? IconImage.ic_checked : IconImage.ic_unchecked
            }
            style={{width: 17, height: 17, marginRight: 5}}
          />
          <View flex>
            <Text style={commonStyles.text_black_13}>
              {cake?.goodsName}
            </Text>
          </View>

          {
            // 已出库状态才能移除 
            cake.status == 1 ? <Button
              style={{width: 60, marginRight: 10, backgroundColor: '#dd001b'}}
              size="xsmall"
              label="移除"
              onPress={() => this.removeCake(cake)}
            /> : null
          }
          <Button
            style={{width: 100}}
            color="#333"
            size="xsmall"
            label="提交异常"
            onPress={() => this.abnormalDialog.show({cake})}
          />
        </View>
        <View row marginT-10>
          <Text>状态：{statusLabelMap[cake.status]}</Text>
        </View>
        <View row marginT-10>
          <TouchableOpacity flex activeOpacity={1} onPress={() => setClipboardContent(cake?.xmbzNo)}>
            <Text>单号：{cake?.xmbzNo}</Text>
          </TouchableOpacity>
          <TouchableOpacity flex activeOpacity={1} onPress={() => setClipboardContent(cake?.warehouseName)}>
            <Text>仓库：{cake?.warehouseName}</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.line} />
      </View>
    );
  };

  render_item = ({item, index}) => {
    logger(item)
    return (
      <View>
        <View style={styles.titleWrap}></View>
        <View style={styles.contentWrap}>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>状态</Text>
            <Text style={statusStyleMap[item?.status]}>
              {statusLabelMap[item?.status]}
            </Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>开始出发时间</Text>
            <Text style={commonStyles.text_black_13}>
              {item?.startTime ? moment(item?.startTime).format('YYYY-MM-DD HH:mm:ss') : '-'}
            </Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>中转完成时间</Text>
            <Text style={commonStyles.text_black_13}>
              {item?.finishTime ? moment(item?.finishTime).format('YYYY-MM-DD HH:mm:ss') : '-'}
            </Text>
          </View>

          {item.transferCakeInfos?.length ? (
            <View>
              {item.transferCakeInfos.map(cake => {
                return this.render_goods_item(cake, item);
              })}
            </View>
          ) : null}
        </View>
      </View>
    );
  };

  render() {
    const {dataList, isRefreshing} = this.state;
    return (
      <View
        useSafeArea
        style={{...commonStyles.body_primary, marginBottom: 32}}>
        <View style={commonStyles.container}>
          <View row centerV>
            <DateFilter
              onQueryClick={(timeStart, timeEnd) =>
                this.setState(
                  {
                    timeStart,
                    timeEnd,
                  },
                  () => this._renderRefresh(),
                )
              }
            />
            <TouchableOpacity
              activeOpacity={1}
              throttleTime={1000}
              style={styles.btn}
              onPress={() => this._renderRefresh()}>
              <Text style={commonStyles.text_black}>刷新</Text>
            </TouchableOpacity>
          </View>
          <FlatList
            data={dataList}
            onRefresh={this._renderRefresh}
            showsVerticalScrollIndicator={false}
            refreshing={isRefreshing}
            extraData={this.state}
            style={{}}
            contentContainerStyle={{flexGrow: 1}}
            keyExtractor={(item, index) => 'menu_' + index}
            renderItem={this.render_item}
            ListEmptyComponent={() => (
              <ListEmpty showEmpty={this.state.showEmpty} />
            )}
          />
        </View>

        <AbnormalDialog ref={r => (this.abnormalDialog = r)}></AbnormalDialog>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  titleWrap: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    alignItems: 'center',
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: '#F9D63B',
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },

  contentWrap: {
    backgroundColor: 'white',
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  reasonWrap: {
    borderBottomLeftRadius: 4,
    borderBottomRightRadius: 4,
    backgroundColor: 'white',
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  itemWrap: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 6,
  },
  itemWrap2: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    paddingVertical: 6,
  },
  line: {
    height: 1,
    backgroundColor: '#EFEFEF',
    marginHorizontal: 15,
  },
  btn: {
    width: 80,
    height: 40,
    ...commonStyles.center,
    backgroundColor: '#F9D63B',
    borderRadius: 5,
  },
});
